package com.qf.homework.day38.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * @author tomyeung-李尐达
 */
public class DBUtil {
    private static String url;
    private static String className;
    private static String password;
    private static String username;

    public DBUtil() {
    }

    //初次加载，获取配置文件
    static {
        Properties properties = new Properties();
        try {
            //加载properties文件，并获取配置信息
            properties.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");
            className=properties.getProperty("className");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static  Connection getConnection(){
        Connection connection = null;
        try {

            Class.forName(className);
             connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    /**
     * 关闭所有资源
     *
     * @param closeables 需要关闭的所有资源
     */
    public static void closeAll(AutoCloseable ...closeables)
    {
        for (AutoCloseable closeable : closeables) {
            if (closeable!=null)
            {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
